﻿using Abp.Application.Services.Dto;
using Abp.Authorization.Users;
using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.EntityFrameworkCore.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.Runtime.Session;
using Abp.UI;
using Camc.Quality.Authorization.Users;
using Camc.Quality.Bom;
using Camc.Quality.Bom.Dto;
using Camc.Quality.BomChange.Dto;
using Camc.Quality.Bop;
using Camc.Quality.Bop.Dto;
using Camc.Quality.Common;
using Camc.Quality.DataDictionary;
using Camc.Quality.IOperationHistory;
using Camc.Quality.Materials;
using Camc.Quality.OperationHistory;
using Camc.Quality.SystemManagement;
using Camc.Quality.WorkFlow;
using EFCore.BulkExtensions;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
namespace Camc.Quality.BomChange
{
    public class BomChangeAppService : QualityAppServiceBase
    {
        private readonly IRepository<MaterialsContent, Guid> _materialsContentRepository;
        private readonly IRepository<Sys_Code, Guid> _sysCodeRepository;
        private readonly IRepository<MaterialsNode, Guid> _materialsNoderepository;
        private readonly IRepository<BomDesign, Guid> _bomDesignrepository;
        private readonly IRepository<BomDesignDetail, Guid> _bomDesignDetailrepository;
        private readonly IAbpSession _abpSession;
        private readonly IRepository<BomChangeContent, Guid> _bomChangeContentrepository;
        private readonly IRepository<User, long> _userRepository;
        public readonly CodeFormatDescAppService _codeFormatDescAppServiceRepsitory;
        private readonly WorkFlowAppService _workFlowAppService;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly IRepository<BusinessApplication, Guid> _businessApplicationRepository;
        private readonly IRepository<WorkFlowNode, Guid> _workFlowNodeRepository;
        private readonly IRepository<WorkAuditor, Guid> _workAuditorRepository;
        private readonly BomContentAppService _bomContentAppService;
        private readonly IRepository<UserRole, long> _userRoleRepository;
        private readonly BomContentAppService _bomContentAppRepository;
        private readonly IOperationHistoryAppService _iOperationHistoryAppService;
        public BomChangeAppService(IUnitOfWorkManager unitOfWorkManager, IRepository<UserRole, long> userRoleRepository,IRepository<MaterialsContent, Guid> materialsContentRepository, IRepository<BomDesign, Guid> bomDesignrepository, IRepository<BomDesignDetail, Guid> bomDesignDetailrepository, IRepository<BomChangeContent, Guid> bomChangeContenrepository, IAbpSession abpSession, IRepository<User, long> userRepository,CodeFormatDescAppService codeFormatDescAppServiceRepsitory, WorkFlowAppService workFlowAppService, BomContentAppService bomContentAppService, IRepository<BusinessApplication, Guid> businessApplicationRepository, IRepository<WorkFlowNode, Guid> workFlowNodeRepository, IRepository<WorkAuditor, Guid> workAuditorRepository, IRepository<Sys_Code, Guid> sysCodeRepository, IRepository<MaterialsNode, Guid> materialsNoderepository, BomContentAppService bomContentApp, IOperationHistoryAppService iOperationHistoryAppService) 
        {
            this._materialsContentRepository = materialsContentRepository;
            this._bomDesignrepository = bomDesignrepository;
            this._bomDesignDetailrepository = bomDesignDetailrepository;
            this._bomChangeContentrepository = bomChangeContenrepository;
            this._abpSession = abpSession;
            this._userRepository = userRepository;
            this._codeFormatDescAppServiceRepsitory = codeFormatDescAppServiceRepsitory;
            this._workFlowAppService  =workFlowAppService;
            this._unitOfWorkManager = unitOfWorkManager;
            this._bomContentAppService = bomContentAppService;
            this._businessApplicationRepository = businessApplicationRepository;
            this._workFlowNodeRepository = workFlowNodeRepository;
            this._workAuditorRepository = workAuditorRepository;
            this._userRoleRepository = userRoleRepository;
            this._materialsNoderepository = materialsNoderepository;
            this._sysCodeRepository = sysCodeRepository;
            this._bomContentAppRepository = bomContentApp;
            this._iOperationHistoryAppService = iOperationHistoryAppService;
        }
        /// <summary>
        /// 根据型号和发次获取版本
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetVersion(BomChangeEditDto bomChangeEditDto)
        {
            //根据型号、发次 、芯级 获取部套
            var queryXjDatas = _bomDesignrepository.FirstOrDefaultAsync(t => t.SendTimeId == bomChangeEditDto.SendTimeId && t.ModuleId == bomChangeEditDto.ModuleId).Result;
            if (queryXjDatas!=null)
            {
                return queryXjDatas.VersionNo;
            }
            return "";
        }
        /// <summary>
        /// 变更保存审核
        /// </summary>
        /// <param name="bomChangeContentDto"></param>
        /// <returns></returns>
        public async Task<ResultMessage> AddToBomChangeContent(BomChangeContentDto bomChangeContentDto,Guid codeFormatId) 
        {
            
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                //根据bomdesign  id 获取版本号
                string version = "";
                int versionInt = 0;
                var queryBomDesignDatas = _bomDesignrepository.FirstOrDefaultAsync(t => t.ModuleId == bomChangeContentDto.ModuleId && t.SendTimeId == bomChangeContentDto.SendTimeId).Result;
                if (queryBomDesignDatas != null)
                {
                    var queryMatralsDatas = _materialsContentRepository.FirstOrDefaultAsync(t => t.Id == queryBomDesignDatas.MaterialsContentId).Result;
                    //if (queryBomDesignDatas != null) 
                    //{
                    // version = queryBomDesignDatas.VersionNo;
                    //截取字符串进行版本变更 
                    if (bomChangeContentDto.BeforeVersion == null)
                    {
                        bomChangeContentDto.BeforeVersion = "01";
                        versionInt = 0;
                    }
                    else 
                    {
                        versionInt = Convert.ToInt32(bomChangeContentDto.BeforeVersion.Right(1));
                    }
                    
                    // }

                    version = "0" + (versionInt + 1).ToString();
                    if (bomChangeContentDto != null)
                    {
                        int queryBomChangeContentCount = _bomChangeContentrepository.Count(t => t.ModuleId == bomChangeContentDto.ModuleId && t.SendTimeId == bomChangeContentDto.SendTimeId && t.MaterialNo == bomChangeContentDto.MaterialNo && t.LaterVersion == version);

                        if (queryBomChangeContentCount > 0)
                        {
                            resultMessage.code = 1;
                            resultMessage.Message = "已存在该变更";
                            return resultMessage;
                            //throw new UserFriendlyException("已存在该变更");
                        }
                        try
                        {
                            bomChangeContentDto.BeforeVersion = bomChangeContentDto.BeforeVersion;
                            bomChangeContentDto.LaterVersion = version;
                            bomChangeContentDto.Status = queryBomDesignDatas.Status;
                            var changeNo = _codeFormatDescAppServiceRepsitory.GetCodeFormat("BOM变更送审");
                            if (changeNo == null)
                            {
                                bomChangeContentDto.ChangeNo = _codeFormatDescAppServiceRepsitory.GetOrderCode("BOMBG", "yyyyMMdd", 1, 5, 1);
                            }
                            else
                            {
                                bomChangeContentDto.ChangeNo = changeNo;
                            }
                            bomChangeContentDto.BomDesignId = queryBomDesignDatas.Id;
                            bomChangeContentDto.MaterialName = queryMatralsDatas.MaterialName;
                            bomChangeContentDto.MaterialNo = queryMatralsDatas.MaterialNo;
                            bomChangeContentDto.Module = bomChangeContentDto.Module;
                            bomChangeContentDto.SendTime = bomChangeContentDto.SendTime;
                            bomChangeContentDto.XJId = bomChangeContentDto.XJId;
                            bomChangeContentDto.CodeId = codeFormatId;

                            queryBomDesignDatas.VersionNo = version;

                            //bomChangeContentDto.Proposer = _abpSession.GetUserId();
                            var bomChangeContent = ObjectMapper.Map<BomChangeContent>(bomChangeContentDto);
                            Guid id = Guid.NewGuid();
                             id= await _bomChangeContentrepository.InsertAndGetIdAsync(bomChangeContent);
                            _iOperationHistoryAppService.InsertOperationLogNew(id, BusinessTypes.设计bom变更, OperationTypes.设计bom变更保存, "【设计bom变更保存未审批】-->型号：" + bomChangeContentDto.Module + "，发次："+ bomChangeContentDto.SendTime+"，芯级:"+ bomChangeContentDto.XJName+ "，部套:" + bomChangeContentDto.BTName + "，变更内容:" + bomChangeContentDto.ChangeContent+ "，变更原因:" +  bomChangeContentDto.ReasonsChangeExplain);
                        }
                        catch
                        {
                            resultMessage.code = 1;
                            resultMessage.Message = "系统错误";
                            return resultMessage;
                            //throw new UserFriendlyException("系统错误");
                        }
                        await _bomDesignrepository.UpdateAsync(queryBomDesignDatas);
                    }
                    //送审
                    //await SendAudit(bomChangeContentDto.bomSendAuditDto);
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        public async Task<Guid> ReutnGuid(BomChangeContentDto bomChangeContentDto, Guid codeFormatId) 
        {
            
            //根据bomdesign  id 获取版本号
            string version = "";
            int versionInt = 0;
            var queryBomDesignDatas = _bomDesignrepository.FirstOrDefaultAsync(t => t.ModuleId == bomChangeContentDto.ModuleId && t.SendTimeId == bomChangeContentDto.SendTimeId).Result;
            var queryBomDesignDetail = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == bomChangeContentDto.BTId).Result;
            if (queryBomDesignDatas != null&& queryBomDesignDetail!=null)
            {
                var queryMatralsDatas = _materialsContentRepository.FirstOrDefaultAsync(t => t.Id == queryBomDesignDatas.MaterialsContentId).Result;
                //if (queryBomDesignDatas != null) 
                //{
                // version = queryBomDesignDatas.VersionNo;
                //截取字符串进行版本变更 
                versionInt = Convert.ToInt32(bomChangeContentDto.BeforeVersion.Right(2));
                // }

                version = "00" + (versionInt + 1).ToString();
                if (bomChangeContentDto != null)
                {
                    //int queryBomChangeContentCount = _bomChangeContentrepository.Count(t => t.ModuleId == bomChangeContentDto.ModuleId && t.SendTimeId == bomChangeContentDto.SendTimeId  &&t.BTId == bomChangeContentDto.BTId&&t.BeforeVersion== bomChangeContentDto.BeforeVersion);

                    //if (queryBomChangeContentCount > 0)
                    //{
                    //    return bomChangeContentDto.Id;
                    //}
                    try
                    {
                        bomChangeContentDto.BeforeVersion = bomChangeContentDto.BeforeVersion;
                        bomChangeContentDto.LaterVersion = version;
                        bomChangeContentDto.Status = (int)queryBomDesignDetail.Status;
                        var changeNo = _codeFormatDescAppServiceRepsitory.GetCodeFormat("BOM变更");
                        if (changeNo == null)
                        {
                            bomChangeContentDto.ChangeNo = _codeFormatDescAppServiceRepsitory.GetOrderCode("BOMBG", "yyyyMMdd", 1, 5, 1);
                        }
                        else
                        {
                            bomChangeContentDto.ChangeNo = changeNo;
                        }
                        bomChangeContentDto.BomDesignId = queryBomDesignDatas.Id;
                        bomChangeContentDto.MaterialName = queryMatralsDatas.MaterialName;
                        bomChangeContentDto.MaterialNo = queryMatralsDatas.MaterialNo;
                        bomChangeContentDto.Module = bomChangeContentDto.Module;
                        bomChangeContentDto.SendTime = bomChangeContentDto.SendTime;
                        bomChangeContentDto.CodeId = codeFormatId;
                        queryBomDesignDatas.VersionNo = version;
                        //bomChangeContentDto.Proposer = _abpSession.GetUserId();
                        var bomChangeContent = ObjectMapper.Map<BomChangeContent>(bomChangeContentDto);

                        //更新设计bom版本
                        await _bomDesignrepository.UpdateAsync(queryBomDesignDatas);
                        await _unitOfWorkManager.Current.SaveChangesAsync();
                        Guid id = Guid.Empty;
                        if (bomChangeContentDto.Id == Guid.Empty)
                        {
                            //bomChangeContentDto.PublishTime = null;
                          id =await _bomChangeContentrepository.InsertAndGetIdAsync(bomChangeContent);
                           
                        }
                        else {
                            bomChangeContent.CreatorUserId = GetCurrentUser().Id; //add 11/30
                            bomChangeContent.CreationTime = DateTime.Now;
                            await _bomChangeContentrepository.UpdateAsync(bomChangeContent);
                            id = bomChangeContent.Id;
                        }
                        await _unitOfWorkManager.Current.SaveChangesAsync();
                        return id;

                    }
                    catch
                    {
                        throw new UserFriendlyException("系统错误");
                    }
                    
                //送审
                //await SendAudit(bomChangeContentDto.bomSendAuditDto);
            }
            }
            return Guid.Empty;
        }
        /// <summary>
        /// 发送审批
        /// </summary>
        private void SendApproval(BomApprovalDto bomApprovalDto)
        {
            //var bomConent = _bomDesignrepository.GetAllIncluding(t => t.BomDesignDetails).Where(d => d.Id == bomApprovalDto.BomId).FirstOrDefault();
            //var bomChangeContent = _bomChangeContentrepository.GetAll().Where(d => d.Id == bomApprovalDto.BomId).FirstOrDefault();
            //var bomAllData = ObjectMapper.Map<BomChangeContentDto>(bomChangeContent);
            //BusinessApplicationDto businessApplicationDto = new BusinessApplicationDto
            //{
            //    AppContent = bomApprovalDto.Remark,
            //    bomChangeContentDto = bomAllData,
            //    BAppType = bomApprovalDto.WfNameId,
            //    FunModule = "工艺管理",
            //    Menu = "BOM变更",
            //    WorkAuditorList = bomApprovalDto.WorkAuditorList
            //};
            //_workFlowAppService.PushBusinessApplication(ObjectMapper.Map<BusinessApplicationDto>(businessApplicationDto));
        }
        /// <summary>
        /// 查询bom变更数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<BomChangeContentDto>> GetBomChangeContent(BomChangeContentSearchDto input) 
        {
            var userData = _userRepository.GetAll().ToList();
            var queryBomChangeContents = from bomChangeContent in _bomChangeContentrepository.GetAll().WhereIf(!input.MaterialNo.IsNullOrWhiteSpace(), t => t.MaterialNo.Contains(input.MaterialNo) )
                                         
                                         join users in userData on bomChangeContent.CreatorUserId equals users.Id
                                         join code2 in _sysCodeRepository.GetAll().WhereIf(!input.Model.IsNullOrWhiteSpace(), t => t.Description.Contains(input.Model)) on bomChangeContent.ModuleId equals code2.Id
                                         //into codeData2
                                         //from cd2 in codeData2.DefaultIfEmpty()
                                         join code3 in _sysCodeRepository.GetAll().WhereIf(!input.SendTime.IsNullOrWhiteSpace(), t => t.Description.Contains(input.SendTime)) on bomChangeContent.SendTimeId equals code3.Id
                                         //            into code3
                                         //from cd3 in code3.DefaultIfEmpty()

                                         select new BomChangeContentDto
                                         {
                                             Id = bomChangeContent.Id,
                                             ChangeNo = bomChangeContent.ChangeNo,
                                             Module = code2.Description,
                                             ModuleId = bomChangeContent.ModuleId,
                                             SendTime = code3.Description,
                                             SendTimeId = bomChangeContent.SendTimeId,
                                             MaterialName = bomChangeContent.MaterialName,
                                             MaterialNo = bomChangeContent.MaterialNo,
                                             Status = (int)bomChangeContent.Status,
                                             BeforeVersion = bomChangeContent.BeforeVersion,
                                             LaterVersion = bomChangeContent.LaterVersion,
                                             Proposer = users.Surname + users.Name,
                                             ApplyForTime = bomChangeContent.CreationTime,
                                             ReasonsChange = bomChangeContent.ReasonsChange,
                                             ReasonsChangeExplain = bomChangeContent.ReasonsChangeExplain,
                                             ChangeContent = bomChangeContent.ChangeContent,
                                             BomDesignId = bomChangeContent.BomDesignId,
                                             PublishTime = bomChangeContent.PublishTime.Value,
                                             XJId = bomChangeContent.XJId,
                                             XJName = bomChangeContent.XJName,
                                             BTId = bomChangeContent.BTId,
                                             BTName = bomChangeContent.BTName,
                                             CodeId =bomChangeContent.CodeId
                                         };
            if (queryBomChangeContents != null&&queryBomChangeContents.Count()>0)
            {
                try
                {
                    var bomChangeContentDataList = await queryBomChangeContents.OrderByDescending(d => d.ApplyForTime).PageBy(input).ToListAsync();
                    return new PagedResultDto<BomChangeContentDto>(queryBomChangeContents.Count(), bomChangeContentDataList);
                }
                catch (Exception ex)
                {
                    throw new UserFriendlyException("系统内部错误,请重试或联系管理员");
                }
            }
            return null;
        }
        /// <summary>
        /// 修改bom变更
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultMessage> UpdateBomChange(BomChangeUpdateDto input) 
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var userDataList = _userRepository.FirstOrDefaultAsync(t => t.Id == GetCurrentUser().Id).Result; //add 11/30
                var bomChangeContents = _bomChangeContentrepository.FirstOrDefaultAsync(t => t.Id == input.Id).Result;
                if (bomChangeContents.CreatorUserId != GetCurrentUser().Id)
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "非本人创建，不能修改！";
                    return resultMessage;
                }
                string version = "";
                int versionInt = 0;
                if (bomChangeContents != null)
                {
                    var queryBomDesignDatas = _bomDesignrepository.FirstOrDefaultAsync(t => t.ModuleId == input.ModuleId && t.SendTimeId == input.SendTimeId).Result;
                    var bomChangeContent = _bomChangeContentrepository.GetAll().Where(t => t.ModuleId == input.ModuleId && t.SendTimeId == input.SendTimeId).OrderByDescending(t => t.CreationTime).FirstOrDefaultAsync().Result;
                    
                    //input.ReasonsChange = bomChangeContents.ReasonsChange;
                    //input.ReasonsChangeExplain = bomChangeContents.ReasonsChangeExplain;
                    //input.ChangeContent = bomChangeContents.ChangeContent;
                    versionInt = Convert.ToInt32(bomChangeContent.LaterVersion.Right(1));
                    version = "0" + (versionInt + 1).ToString();
                    // input.ChangeNo = _codeFormatDescAppServiceRepsitory.GetCodeFormat(input.CodeId);
                    input.LaterVersion = version;
                    input.BomDesignId = queryBomDesignDatas.Id;
                    var changeNo = _codeFormatDescAppServiceRepsitory.GetCodeFormat("BOM变更");
                    if (changeNo == null)
                    {
                        input.ChangeNo = _codeFormatDescAppServiceRepsitory.GetOrderCode("BOMBG", "yyyyMMdd", 1, 5, 1);
                    }
                    else
                    {
                        input.ChangeNo = changeNo;
                    }
                    input.MaterialName = bomChangeContents.MaterialName;
                    input.MaterialNo = bomChangeContents.MaterialNo;
                    var bomChangeContentNew = ObjectMapper.Map(input, bomChangeContents);
                    await _bomChangeContentrepository.UpdateAsync(bomChangeContentNew);
                    _iOperationHistoryAppService.InsertOperationLogNew(bomChangeContentNew.Id, BusinessTypes.设计bom变更, OperationTypes.设计bom变更修改, "【修改】-->型号：" + bomChangeContentNew.Module + "，发次：" + bomChangeContentNew.SendTime + "，芯级:" + bomChangeContentNew.XJName + "，部套：" + bomChangeContentNew.BTName + "，变更内容:" + bomChangeContentNew.ChangeContent + "，变更原因:" + bomChangeContentNew.ReasonsChangeExplain);
                    //送审
                    //await SendAudit(input.bomSendAuditDto);
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 删除变更bom
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ResultMessage> DeleBomNode(Guid id)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                var userDataList = _userRepository.FirstOrDefaultAsync(t => t.Id == GetCurrentUser().Id).Result; //add 11/30
                var bomChangeContentlList = _bomChangeContentrepository.FirstOrDefaultAsync(t => t.Id == id).Result;
                if (bomChangeContentlList.CreatorUserId != GetCurrentUser().Id)
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "非本人创建，不能删除！";
                    return resultMessage;
                }
                if (bomChangeContentlList != null)
                {
                    await _bomChangeContentrepository.DeleteAsync(id);
                 
                }
                else
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "无对应变更BOM数据!";
                    return resultMessage;
                    //throw new UserFriendlyException("无对应变更BOM数据!");
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 查询单条明细
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public async Task<List<BomChangeContentDto>> GetBomChangeSearchOne(Guid bappId) 
        {
            var workAuditorList = _workAuditorRepository.GetAll().Where(d => d.BappId == bappId);
            List<WorkAuditorOutput> workAuditorOutputs = null;
            var users = _userRepository.GetAll().ToList();
            workAuditorOutputs = (from tempQy in workAuditorList
                               join wf in _workFlowNodeRepository.GetAll() on tempQy.WfID equals wf.WfID
                               join user in users on tempQy.UserId equals user.Id
                               where wf.WnID == tempQy.WnID
                               select new WorkAuditorOutput
                               {
                                   BappId = tempQy.BappId,
                                   WfName = wf.WnName,
                                   UserName = user.UserName,
                                   Result = tempQy.Result,
                                   Remark = tempQy.Remark,
                                   AuditTime = tempQy.AuditTime
                               }).ToList();
            var queryBomChangeContents = from bomChangeContent in _bomChangeContentrepository.GetAll().Where(t => t.ChangesAuditId == bappId)
                                         select new BomChangeContentDto
                                         {
                                             Id = bomChangeContent.Id,
                                             ChangeNo = bomChangeContent.ChangeNo,
                                             Module = bomChangeContent.Module,
                                             ModuleId = bomChangeContent.ModuleId,
                                             SendTime = bomChangeContent.SendTime,
                                             SendTimeId = bomChangeContent.SendTimeId,
                                             MaterialName = bomChangeContent.MaterialName,
                                             MaterialNo = bomChangeContent.MaterialNo,
                                             Status = (int)bomChangeContent.Status,
                                             BeforeVersion = bomChangeContent.BeforeVersion,
                                             LaterVersion = bomChangeContent.LaterVersion,
                                             //Proposer = users.UserName,
                                             ApplyForTime = bomChangeContent.CreationTime,
                                             ReasonsChange = bomChangeContent.ReasonsChange,
                                             ReasonsChangeExplain = bomChangeContent.ReasonsChangeExplain,
                                             ChangeContent = bomChangeContent.ChangeContent,
                                             BomDesignId = bomChangeContent.BomDesignId,
                                             PublishTime = bomChangeContent.PublishTime.Value,
                                             XJId = bomChangeContent.XJId,
                                             XJName = bomChangeContent.XJName,
                                             BTId = bomChangeContent.BTId,
                                             CodeId = bomChangeContent.CodeId,
                                             workAuditorOutput = workAuditorOutputs
                                         };
            if (queryBomChangeContents!=null) 
            {
                return queryBomChangeContents.ToList();
            }
            return new List<BomChangeContentDto>();
        }
        /// <summary>
        /// 保存送审
        /// </summary>
        public async Task<ResultMessage> SendAudit(BomApprovalDto input)
        {
            ResultMessage resultMessage = new ResultMessage();
            try
            {
                //if (input.CreateFlag == 0)d.Status == DocumentStatus.编制中 ||
                //{
                var bomChangeModif = _bomChangeContentrepository.GetAll().Where(d => d.BTId == input.BomId && (d.Status == DocumentStatus.审核中)).FirstOrDefault();
                if (bomChangeModif != null)
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "存有发起变更同一个设计bom变更业务";
                    return resultMessage;
                    //throw new UserFriendlyException("存有发起变更同一个设计bom变更业务");
                }
                Guid id = await ReutnGuid(input.bomChangeContentDto, Guid.Empty);
                //_unitOfWorkManager.Current.SaveChanges();
                var bomDesignDetailContent = _bomChangeContentrepository.FirstOrDefault(t => t.Id == id);
                if (bomDesignDetailContent.CreatorUserId != GetCurrentUser().Id) //add 11/30
                {
                    resultMessage.code = 1;
                    resultMessage.Message = "非本人创建，不能送审！";
                    return resultMessage;
                    //throw new UserFriendlyException("非本人创建，不能送审！");
                }
                var bomDesignDetail = _bomDesignDetailrepository.FirstOrDefaultAsync(t => t.Id == bomDesignDetailContent.BTId).Result;
                var bomChangeContent = _bomChangeContentrepository.Get(id);
                if (bomChangeContent != null)
                {
                    if (bomChangeContent.Status == DocumentStatus.被驳回)
                    {
                        RejectPushBusInput reject = new RejectPushBusInput();
                        reject.WorkAuditorList = input.WorkAuditorList;
                        reject.Type = input.Type;
                        reject.Id = bomDesignDetail.ModifiChangeId;
                        _workFlowAppService.RejectPushBusinessApplication(reject);
                        bomDesignDetailContent.Status = DocumentStatus.审核中; //add 12/1
                        bomDesignDetailContent.ChangesAuditId = bomDesignDetail.ModifiChangeId;
                        await _bomChangeContentrepository.UpdateAsync(bomDesignDetailContent);
                        //日志
                        _iOperationHistoryAppService.InsertOperationLogNew(bomChangeContent.Id, BusinessTypes.设计bom变更审核, OperationTypes.设计bom变更审批驳回后送审, "【审批】-->型号：" + bomChangeContent.Module + "，发次：" + bomChangeContent.SendTime + "，芯级:" + bomChangeContent.XJName + "，部套：" + bomChangeContent.BTName + "，变更内容:" + bomChangeContent.ChangeContent + "，变更原因:" + bomChangeContent.ReasonsChangeExplain + "，状态：" + bomChangeContent.Status);
                    }
                    else
                    {
                        PushBusInput push = new PushBusInput();
                        push.WorkAuditorList = input.WorkAuditorList;
                        push.Type = input.Type; //发起审核默认  变更工艺规程流程为0
                        push.FunModule = "变更管理";
                        push.Menu = "bom变更管理";
                        push.BusinessNumber = bomDesignDetailContent.ChangeNo;
                        var queryXhFc = _bomDesignrepository.FirstOrDefaultAsync(t => t.Id == bomDesignDetail.BomDesignId).Result;
                        string codes = "";
                        if (queryXhFc != null) {
                            var querySysCodes = _sysCodeRepository.FirstOrDefaultAsync(t=>t.Id ==queryXhFc.SendTimeId).Result;
                            codes = querySysCodes.Description;
                            push.BusinessDesc = "型号：" + queryXhFc.Module + "，发次：" + codes + "，芯级：" + bomDesignDetailContent.XJName + "，部套：" + bomDesignDetailContent.BTName;
                        }
                        Guid busId = _workFlowAppService.PushBusinessApplication(push);

                        if (bomDesignDetailContent != null)
                        {
                            bomDesignDetailContent.ChangesAuditId = busId;
                            bomDesignDetail.Status = DocumentStatus.审核中;
                            bomDesignDetail.ModifiChangeId = busId;
                            bomDesignDetailContent.Status = DocumentStatus.审核中;
                            await _bomContentAppRepository.SendAuditUpdateStatus(bomDesignDetail);
                            await _bomChangeContentrepository.UpdateAsync(bomDesignDetailContent);
                            //日志
                            _iOperationHistoryAppService.InsertOperationLogNew(bomDesignDetailContent.Id, BusinessTypes.设计bom变更审核, OperationTypes.设计bom变更送审, "【送审】-->型号：" + bomDesignDetailContent.Module + "，发次：" + codes + "，芯级:" + bomDesignDetailContent.XJName + "，部套：" + bomDesignDetailContent.BTName + "，变更内容:" + bomDesignDetailContent.ChangeContent + "，变更原因:" + bomDesignDetailContent.ReasonsChangeExplain+"，状态："+ bomDesignDetailContent.Status);
                        }
                    }
                }
                resultMessage.code = 0;
                return resultMessage;
            }
            catch (Exception ex)
            {
                resultMessage.code = 1;
                resultMessage.Message = ex.Message;
                return resultMessage;
            }
        }
        /// <summary>
        /// 根据业务Id查询变更管理业务详情
        /// </summary>
        /// <param name="bappId"></param>
        /// <returns></returns>
        public BomModifResult DisplayChangeBomBusinessById(Guid bappId)
        {
            BomModifResult result = new BomModifResult();
            var bomChangeContent = _bomChangeContentrepository.FirstOrDefault(d => d.ChangesAuditId == bappId);
            if (bomChangeContent != null)
            {
                var business = _businessApplicationRepository.Get(bappId);
                var workNode = _workFlowNodeRepository.GetAll().First(d => d.WnID == business.BAppType && d.WfID == business.Status);
                var workAuditorList = _workAuditorRepository.GetAll().Where(d => d.BappId == bappId);
                var currentUser = GetCurrentUser();
                var currentRoles = _userRoleRepository.GetAll().Where(userRole => userRole.UserId == currentUser.Id).Select(userRole => userRole.RoleId).ToArray();
                if (workNode.NextNode == "0")
                {//业务结束只能查看
                    result.DisplayApproval = false;
                }
                else if ((currentUser.Id == business.ExamineUserId)/*|| (currentUser.Roles.Select(d => d.RoleId).Contains(Convert.ToInt32(workNode.Handlers)) && currentUser.Id != business.UserID)*/)
                {//处理用户业务的节点
                    result.DisplayApproval = true;
                }
                else if (currentRoles.Length > 0)
                {
                    string[] bigArr = Array.ConvertAll(currentRoles, _ => _.ToString());

                    var smallArr = workNode.Handlers.Split(',').ToArray();
                    var exceptArr = bigArr.Intersect(smallArr);
                    if (exceptArr.Any())
                    {
                        if (business.ExamineUserId == null)
                        {
                            result.DisplayApproval = true;
                        }
                    }

                }
                else
                {//非本人处理，只是查看
                    result.DisplayApproval = false;
                }
                var users = _userRepository.GetAll().ToList();
                BomDetaillist bomDetaillist = new BomDetaillist();
                GetBomNodeTreeListInput getBomNodeTreeListInput = new GetBomNodeTreeListInput();
                getBomNodeTreeListInput.BomId = bomChangeContent.BTId;
                bomDetaillist = _bomContentAppService.GetBomChildTreeGrid(getBomNodeTreeListInput);
                result.BomDetaillists = bomDetaillist;
                result.WorkAuditorList = (from tempQy in workAuditorList
                                          join wf in _workFlowNodeRepository.GetAll() on tempQy.WfID equals wf.WfID
                                          join user in users on tempQy.UserId equals user.Id
                                          where wf.WnID == tempQy.WnID
                                          select new WorkAuditorOutput
                                          {
                                              BappId = tempQy.BappId,
                                              WfName = wf.WnName,
                                              UserName = user.UserName,
                                              Result = tempQy.Result,
                                              Remark = tempQy.Remark,
                                              AuditTime = tempQy.AuditTime
                                          }).ToList();
            }
            return result;
        }

        /// <summary>
        /// 审批变更管理
        /// </summary>
        /// <param name="input"></param>
        public void ApproveChangeBomModif(ApproveInput input)
        {
            int status = 0;
            _workFlowAppService.SendToFlow(input.BappId, input.Operation, input.Remark, out status);
            List<BomDesignDetail> bomDesignDetailList = new List<BomDesignDetail>();
            if (status == 99)
            {
                var modif = _bomChangeContentrepository.GetAll().Where(d => d.ChangesAuditId == input.BappId).FirstOrDefault();
                var bomDesignDetail = _bomDesignDetailrepository.GetAll().Where(t => t.ModifiChangeId == input.BappId);
                modif.Status = DocumentStatus.已发布;
                modif.PublishTime =DateTime.Now;
                if (bomDesignDetail != null && bomDesignDetail.Count() > 0)
                {
                    foreach (BomDesignDetail bomDesignDetailOne in bomDesignDetail)
                    {
                        bomDesignDetailOne.Status = DocumentStatus.已发布;
                        bomDesignDetailList.Add(bomDesignDetailOne);
                    }
                    _bomDesignDetailrepository.GetDbContext().BulkUpdate(bomDesignDetailList);
                }
                _bomChangeContentrepository.Update(modif);
                //日志
                _iOperationHistoryAppService.InsertOperationLogNew(modif.Id, BusinessTypes.设计bom变更审核, OperationTypes.设计bom变更审批通过, "【审批】-->型号：" + modif.Module + "，发次：" + modif.SendTime + "，芯级:" + modif.XJName + "，部套：" + modif.BTName + "，变更内容:" + modif.ChangeContent + "，变更原因:" + modif.ReasonsChangeExplain + "，状态：" + modif.Status);
            }
            if (status == 100)
            {
                var modif = _bomChangeContentrepository.GetAll().Where(d => d.ChangesAuditId == input.BappId).FirstOrDefault();
                var bomDesignDetail = _bomDesignDetailrepository.GetAll().Where(t => t.ModifiChangeId == input.BappId);
                if (bomDesignDetail != null && bomDesignDetail.Count() > 0)
                {
                    foreach (BomDesignDetail bomDesignDetailOne in bomDesignDetail)
                    {
                        bomDesignDetailOne.Status = DocumentStatus.被驳回;
                        bomDesignDetailList.Add(bomDesignDetailOne);
                    }
                    _bomDesignDetailrepository.GetDbContext().BulkUpdate(bomDesignDetailList);
                }
                modif.Status = DocumentStatus.被驳回;
                _bomChangeContentrepository.Update(modif);
                //日志
                _iOperationHistoryAppService.InsertOperationLogNew(modif.Id, BusinessTypes.设计bom变更审核, OperationTypes.设计bom变更审批通过, "【审批】-->型号：" + modif.Module + "，发次：" + modif.SendTime + "，芯级:" + modif.XJName + "，部套：" + modif.BTName + "，变更内容:" + modif.ChangeContent + "，变更原因:" + modif.ReasonsChangeExplain + "，状态：" + modif.Status);
            }
        }

        /// <summary>
        /// 设计bom变更新增物料子级模态框
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<BomMainSelectParentContentListDto>> GetSelectChildMaterialsContentChange(BomChangeAddChildDto input)
        {
            try
            {
                //找出物料类型不是一级和二级的物料
                var queryMaterialsContent = (from materialsContent in _materialsContentRepository.GetAll().Where(t => t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.组件 || t.MaterialProperty == (int)MaterialsEnum.MaterialProperty.零件)
                                             join materialsNode in _materialsNoderepository.GetAll() on materialsContent.MaterialsNodeId equals materialsNode.Id into mm
                                             from Joinmm in mm.DefaultIfEmpty()
                                             join materialsNodeSegmentation in _materialsNoderepository.GetAll() on materialsContent.MaterialCategoryId equals materialsNodeSegmentation.Id
                                             into mn
                                             from Joinmn in mn.DefaultIfEmpty()
                                             join bomDesign in _bomDesignrepository.GetAll() on materialsContent.Id equals bomDesign.MaterialsContentId
                                             into bm
                                             from Joinbm in bm.DefaultIfEmpty()
                                             join code in _sysCodeRepository.GetAll() on materialsContent.UnitId equals code.Id
                     into codeData
                                             from cd in codeData.DefaultIfEmpty()
                                             join code2 in _sysCodeRepository.GetAll() on Joinbm.ModuleId equals code2.Id
                           into codeData2
                                             from cd2 in codeData2.DefaultIfEmpty()
                                             join code3 in _sysCodeRepository.GetAll() on Joinbm.SendTimeId equals code3.Id
                                                         into code3
                                             from cd3 in code3.DefaultIfEmpty()
                                             select new BomMainSelectParentContentListDto
                                             {
                                                 Id = materialsContent.Id,
                                                 MaterialTypeId = Joinmm.Id,
                                                 MaterialNo = materialsContent.MaterialNo,
                                                 MaterialName = materialsContent.MaterialName,
                                                 Model = materialsContent.Model,
                                                 MaterialTypeName = Joinmm.MaterialTypeName,
                                                 MaterialSegmentationName = Joinmn.MaterialTypeName,
                                                 VersionNo = Joinbm.VersionNo,
                                                 UnitId = materialsContent.UnitId,
                                                 IsKeyPart = Enum.Parse(typeof(MaterialsEnum.IsKeyPart), materialsContent.IsKeyPart.ToString()).ToString(),
                                                 Remark = materialsContent.Remark,
                                                 UnitName = cd.Code,
                                                 Attribute = materialsContent.MaterialProperty,
                                                 SendTime = cd3.Description
                                             })
                                             .WhereIf(!string.IsNullOrEmpty(input.MaterialNo), d => d.MaterialNo == input.MaterialNo) //add 11/30
                                             .WhereIf(!string.IsNullOrEmpty(input.MaterialName), d => d.MaterialName == input.MaterialName); //add 11/30;
                if (queryMaterialsContent != null)
                {
                    var materialsContentDataList = await queryMaterialsContent.OrderBy(t=>t.Attribute).PageBy(input).ToListAsync();
                    return new PagedResultDto<BomMainSelectParentContentListDto>(queryMaterialsContent.Count(), materialsContentDataList);
                }
            }
            catch (Exception)
            {
                throw new UserFriendlyException("内部错误");
            }
            return new PagedResultDto<BomMainSelectParentContentListDto>();
        }
    }
}
